import ImageCompressor from './image-compressor.min'

// <=1MB的图片不压缩
const ignoreSize = 1048576 // 单位Bytes

export function compressImg({file, success, fail}) {
    if (!file) {
        fail('要压缩的图片文件不能为空')
    }
    if (file.size <= ignoreSize){
        success(file)
        return
    }
    let options = {
        file,
        // 默认0.8
        quality: 0.6,
        // 压缩前回调
        beforeCompress: (result) => {
            // console.log('压缩之前图片尺寸大小: ', (parseInt(result.size / 1024)));
            // console.log('mime 类型: ', result.type);
        },
        // 压缩成功回调
        success: (result) => {
            // console.log('result: ', result)
            // console.log('压缩之后图片尺寸大小: ', (parseInt(result.size / 1024)));
            // console.log('mime 类型: ', result.type);
            // console.log('实际压缩率： ', ((file.size - result.size) / file.size * 100).toFixed(2) + '%');
            if (success && success instanceof Function) {
                success(result)
            }
        },
        // 发生错误
        error: function (msg) {
            if (fail && fail instanceof Function) {
                fail(msg)
            }
            uni.showToast({
                icon: "none",
                title: "压缩图片错误",
            });
        }
    }
    new ImageCompressor(options);
}
